#include <bits/stdc++.h>

using namespace std;

const int N = 1e5 + 10;

map<string,string> mp;

string find(string x){
    if(x != mp[x])return mp[x] = find(mp[x]);
    return x;
}

void merge(string x,string y){
    string xx = find(x);
    string yy = find(y);
    if(xx != yy)mp[yy] = xx;
}


int main()
{
    string t;
    while(1){
        string x;
        cin >> x;
        char op = x[0];
        string xx = x.substr(1,x.size());
        // cout << "op:" <<op <<" Xx:" << xx <<'\n';
        if(mp.count(xx) == 0){
            mp[xx] = xx;
            // cout <<"xx:" << xx<< '\n';
        }
        if(op == '#'){
           t = xx;
        }
        else if(op == '+'){
             merge(t,xx);
        }
        else if(op == '?'){
            cout << xx << " " << find(xx) <<'\n';
        } else
         if(op == '$')break;
    }
   
   return 0;
}
